<!-- 标签选项卡容器 -->
<template>
	<div class="tab-bar">
		<el-tabs v-model="activeName" @tab-click="tabClick" @tab-remove="tabRemove">
			<el-tab-pane v-for="tab in tabs" :key="tab.name" :label="tab.label" :name="tab.name" :closable="tab.closable"></el-tab-pane>
		</el-tabs>
	</div>
</template>

<script>
export default {
	name: "TabBar",
	props: {
		home: {
			type: Object,
			default: () => ({name: "home", label: "首页", path: "/home", closable: false})
		}
	},
	data() {
		return {
			tabs: [this.home],
			activeName: ""
		}
	},
	watch: {
		// 监控route改变，动态添加tab
		"$route": {
			handler(to) {
				console.log(to)
				let flag = true;	// 标记是否需要增加Tab
				// let componentName;
				const name = to.name;
				const path = to.fullPath;

				if (name) {
					for (let tab of this.tabs) {
						if (tab.name === name) {
							// this.activeName = name;
							// componentName = tab.componentName;
							flag = false;
							break
						}
					}

					// 添加Tab
					if (flag) {
						// componentName = to.meta.componentName;
						this.tabs.push({
							label: to.meta.title,
							name,
							path,
							// componentName,
							closable: true
						})
					}

					this.activeName = name;

					// this.$emit("change", componentName)
				}
			},
			immediate: true
		}
	},
	methods: {
		tabClick(active) {
			let [tab] = this.tabs.filter(val => val.name === active.name);
			this.$router.push({
				path: tab.path
			})
		},
		tabRemove(targetName) {
			if (this.activeName === targetName) {
				this.tabs.forEach((tab, index) => {
					if (tab.name === targetName) {
						let next = this.tabs[index - 1] || this.tabs[index + 1];
						if (next) {
							this.activeName = next.name;
							// this.tabClick(next);
							this.$router.push({
								path: next.path
							})
						}
					}
				})
			}
			this.tabs = this.tabs.filter(val => val.name !== targetName)
		}
	}
}
</script>

<style>
.tab-bar {
	padding: 12px 8px;
}

.tab-bar .el-tabs__nav-wrap::after {
	height: 0;
}

.el-tabs__header {
	margin: 0;
}

.tab-bar .el-tabs__item {
	/* background-color: #ccc; */
	padding: 0 20px !important;
	margin: 0 4px;
	border: 1px solid #ccc;
	border-radius: 4px;
	height: 32px;
	line-height: 32px;
	background-color: #eee;
}

.tab-bar .el-tabs__active-bar {
	display: none;
}

.el-tabs__nav-next, .el-tabs__nav-prev {
	line-height: 32px;
}
</style>
